// 该组件为通用文件上传组件，被多个页面复用，已归类到 common 目录
<script setup lang="ts">
  import 'vue-cropper/dist/index.css'
  import { VueCropper } from 'vue-cropper'
  import { ref, watch } from 'vue'
  import { UploadFile } from 'element-plus'
  import { compress } from 'image-conversion'
  import { getImageScale } from '@/utils/file-util.ts'

  const { upload, fileName, img } = defineProps({
    show: {
      type: Boolean,
      required: false,
      default: true,
    },
    cropHeight: {
      type: [Number, String],
      required: false,
      default: 0,
    },
    cropWeight: {
      type: [Number, String],
      required: false,
      default: 0,
    },
    upload: {
      type: Function,
      required: true,
    },
    img: {
      type: String,
      required: false,
      default: '',
    },
    fileName: {
      type: String,
      required: false,
      default: '',
    },
  })
  /*原始图片资源*/
  const uploadSrc = ref()
  const imgSrc = ref(img)

  /*看父组件传递过来的和上传的哪个最后更新赋值哪个*/
  watch(
    () => [img, uploadSrc.value],
    ([n1, n2], [o1, o2]) => {
      if (n1 != o1) {
        imgSrc.value = n1
      }
      if (n2 != o2) {
        imgSrc.value = n2
      }
    }
  )

  /*截图组件*/
  const cropper = ref()
  /*上传的文件*/
  const uploadFile = ref()
  const handleChange = (file: UploadFile) => {
    uploadFile.value = file
    const raw = file.raw
    if (raw) {
      uploadSrc.value = URL.createObjectURL(raw)
    }
  }
  const handleUpload = () => {
    cropper.value.getCropBlob(async (data: Blob) => {
      let name = uploadFile.value?.name
      name = name ? name : fileName
      //缩小比例
      const scale = await getImageScale(512, data)
      const res = await compress(data, { quality: 1, scale })
      upload(new File([res], name))
    })
  }
</script>

<template>
  <section v-if="show" class="crop-wrap">
    <VueCropper
      ref="cropper"
      center-box
      :img="imgSrc"
      auto-crop
      fixed
      can-move
      :auto-crop-height="cropHeight ? cropHeight : cropWeight"
      :auto-crop-width="cropWeight ? cropWeight : cropHeight"
      :can-move-box="false"
    >
      <template #loading>
        <p>加载中...</p>
      </template>
    </VueCropper>
  </section>
  <section class="crop-upload">
    <el-upload
      class="upload-demo"
      :auto-upload="false"
      accept="image/*"
      :show-file-list="false"
      @change="handleChange"
    >
      <template #trigger>
        <el-button type="primary">选择图片</el-button>
      </template>
    </el-upload>
    <span style="width: 30px"></span>
    <el-button @click="handleUpload">上传并保存</el-button>
  </section>
</template>

<style scoped>
  .crop-wrap {
    width: 300px;
    height: 300px;
    margin-bottom: 20px;
  }

  .crop-upload {
    position: relative;
    display: flex;
    flex-direction: row;
  }
</style>
